package com.sfx.concurrent.demo.concurrent.AtomicTest.Account;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-19
 * Time: 19:25
 */
public class AccountSafe implements Account{
    private AtomicInteger balance;

    public AccountSafe(int balance) {
        this.balance = new AtomicInteger(balance);
    }

    @Override
    public Integer getBalance() {
        return balance.get();
    }

    @Override
    public void withDraw(int account) {
        while(true) {
            int prev = balance.get();
            int next = prev - account;
            if(balance.compareAndSet(prev,next)) {
                break;
            }
        }
    }

    public static void main(String[] args) {
        AccountSafe accountSafe = new AccountSafe(10000);
        Account.demo(accountSafe);
    }
}
